/**
 *  json响应处理
 */

const document = require('./document.js')

// 返回数据解析
const getResultJsonStr = (code = -1, data = '', msg = '',  page = {}) => {
    if(Object.keys(page).length){
        return {
            status: code === 200 ? 'ok' : 'error',
            msg:  msg || document.list[code] || document.list[-1],
            code,
            data,
            page
        }
    } else {
        return {
            status: code === 200 ? 'ok' : 'error',
            msg:  msg || document.list[code] || document.list[-1],
            code,
            data
        }
    }
}

// 返回header设置
const sendJson = (response, json) => {
    response.writeHead(200, {
        "Access-Control-Allow-Headers": "Content-Type, X-CSRF-Token, X-Requested-With, Accept, Accept-Version, Content-Length, Content-MD5,  Date, X-Api-Version, X-File-Name",
        'Access-Control-Allow-Origin': '*',
        'Access-Control-Allow-Methods': 'PUT,POST,GET,DELETE,OPTIONS',
        'Access-Control-Allow-Credentials': true,
        'Content-Type': 'text/html;charset:utf-8'
    })
    response.end(JSON.stringify(json))
}

// 统一返回函数
const sendResult = (response, code = -1, data = '', msg = '', page) => {
    sendJson(response, getResultJsonStr(code, data, msg, page))
}

module.exports = {
    sendResult: sendResult
}